"""
参数验证模块
"""

import re
from typing import Dict, List, Any
from functools import wraps
from flask import request
from .response import error_response


def validate_required(fields: List[str]):
    """
    验证必需字段装饰器
    
    Args:
        fields: 必需字段列表
    """
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            # 获取请求数据
            if request.is_json:
                data = request.get_json()
            else:
                data = request.form.to_dict()
            
            # 检查必需字段
            missing_fields = []
            for field in fields:
                if field not in data or data[field] is None or data[field] == '':
                    missing_fields.append(field)
            
            if missing_fields:
                return error_response(f"缺少必需字段: {', '.join(missing_fields)}", 400)
            
            return func(*args, **kwargs)
        return wrapper
    return decorator


def validate_url(url: str) -> bool:
    """
    验证URL格式
    
    Args:
        url: URL字符串
        
    Returns:
        是否有效
    """
    if not url:
        return False
    
    # URL正则表达式
    url_pattern = re.compile(
        r'^https?://'  # http:// or https://
        r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?|'  # domain...
        r'localhost|'  # localhost...
        r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'  # ...or ip
        r'(?::\d+)?'  # optional port
        r'(?:/?|[/?]\S+)$', re.IGNORECASE)
    
    return url_pattern.match(url) is not None


def validate_method(method: str) -> bool:
    """
    验证HTTP方法
    
    Args:
        method: HTTP方法
        
    Returns:
        是否有效
    """
    valid_methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS']
    return method.upper() in valid_methods


def validate_json_field(data: Dict, field: str, field_type: type, required: bool = True) -> tuple:
    """
    验证JSON字段
    
    Args:
        data: 数据字典
        field: 字段名
        field_type: 字段类型
        required: 是否必需
        
    Returns:
        (是否有效, 错误消息)
    """
    if field not in data:
        if required:
            return False, f"缺少必需字段: {field}"
        return True, ""
    
    value = data[field]
    
    if value is None:
        if required:
            return False, f"字段不能为空: {field}"
        return True, ""
    
    if not isinstance(value, field_type):
        return False, f"字段类型错误: {field} 应为 {field_type.__name__}"
    
    return True, ""
